package com.testmanager.testmananger.practiseDemo.taskWork;

import com.testmanager.testmananger.foundation.util.FileUtils;
import com.testmanager.testmananger.shuiyou.common.Constant.RedisFileName;
import com.testmanager.testmananger.shuiyou.common.util.JUDANRedisFileManager;
import com.testmanager.testmananger.shuiyou.common.util.OtherRedis;
import com.testmanager.testmananger.shuiyou.szjk.domain.ZipFileEntity;
import com.testmanager.testmananger.shuiyou.szjk.dto.ZipDto;
import com.testmanager.testmananger.shuiyou.szjk.dto.ZipFileDto;
import com.testmanager.testmananger.shuiyou.szjk.mapper.ZipFileMapper;
import com.testmanager.testmananger.shuiyou.szjk.mapper.ZipMapper;
import com.testmanager.testmananger.shuiyou.szjk.repository.ZipFileRepository;
import com.testmanager.testmananger.shuiyou.szjk.repository.ZipRepository;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DownService {


    @Autowired
    ZipRepository zipRepository;
    @Autowired
    ZipFileRepository zipFileRepository;

//    @Resource(name = "juduanFilesJSONObject")
////    JSONObject redisjsonFiles;

    @Autowired
    OtherRedis otherRedis;

    @Autowired
    JUDANRedisFileManager judanRedisFileManager;

    //FileUtils fileUtils = new FileUtils();

    @SuppressWarnings
    public ResponseEntity upload(long typeid, MultipartFile file) {

        if (!file.isEmpty() && file.getOriginalFilename().toUpperCase().contains(".ZIP")) {
            String fileName = file.getOriginalFilename();
            if (null != zipRepository.findByName(fileName)) {
                return ResponseEntity.ok("文件名已存在");
            }


            ZipDto zipDto = new ZipDto();
            ZipFileEntity zipFileEntity;
            String path = "";

            String subfileName = "";

            String truefileNmae = fileName;
            path = FileUtils.BASEPATH + truefileNmae;

            File dest = new File(path);

            if (dest.getParentFile() != null && !dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }


            try {
                file.transferTo(dest);
                ZipFile zipFile = new ZipFile(dest);
                zipFile.setFileNameCharset("UTF-8");
                System.out.println(file.getOriginalFilename());
                zipFile.extractAll(FileUtils.BASEPATH);
                zipDto.setName(new String(file.getOriginalFilename().getBytes(), "utf-8")).setType(typeid);
                long zipId = zipRepository.save(ZipMapper.toZipEntity(zipDto)).getId();

                List<FileHeader> fileHeaders = zipFile.getFileHeaders();
                for (FileHeader fileHeader : fileHeaders) {
                    //  fileName.endsWith("/") || fileName.endsWith("\\\\") || fileName.endsWith("\\")
                    if (!fileHeader.getFileName().endsWith(File.pathSeparator)) {
                        zipFileEntity = new ZipFileEntity();
                        subfileName = fileHeader.getFileName();
                        zipFileEntity.setName(subfileName).setZipId(zipId).setContent(FileUtils.file2str(FileUtils.BASEPATH + subfileName));
                        // System.out.println(subfileName);
                        zipFileRepository.save(zipFileEntity);


                    }


                }


                FileUtils.removeDir(new File(FileUtils.BASEPATH));


            } catch (Exception e) {

                e.printStackTrace();
                return ResponseEntity.status(500).body(e.getMessage());
            }


            return ResponseEntity.ok("成功");
        }
        return ResponseEntity.status(500).body("文件格式不为zip或不存在！");

    }


    public List<ZipFileDto> getJuduanFiles(ZipDto zipDto) {
        List<ZipFileDto> list = getZipFiles(zipDto);
        ZipFileDto base = new ZipFileDto();
        ZipFileDto cwbb = new ZipFileDto();
        base.setName(RedisFileName.BASE).setContent(judanRedisFileManager.getRedisFIlesJSONObject().getString(RedisFileName.BASE));
        cwbb.setName(RedisFileName.CWBB).setContent(judanRedisFileManager.getRedisFIlesJSONObject().getString(RedisFileName.CWBB));
        list.add(base);
        list.add(cwbb);
        return list;
    }


    public List<ZipFileDto> getZipFiles(ZipDto zipDto) {
        //增加 redis 选项  和oracle 选项
//        ZipFileDto zipFileDto = new ZipFileDto();
//        zipFileDto.setName("redis").setContent("redis").setId(-10);
//        ZipFileDto zipFileDto1 = new ZipFileDto();
//        zipFileDto1.setName("oracle").setContent("oracle").setId(-20);
        List<ZipFileDto> list = zipFileRepository.findAllByZipId(zipDto.getId())
                .stream()
                .map(ZipFileMapper::toZipFileDto)
                .collect(Collectors.toList());

//        list.add(zipFileDto);
//        list.add(zipFileDto1);
        return list;

    }


    public List<ZipDto> getZipDtos() {

        return zipRepository.findAll()
                .stream()
                .map(zipEntity -> {
                    return ZipMapper.toZipDtoWithFiles(zipEntity, null);
                }).collect(Collectors.toList());
    }

    /**
     * 级连
     *
     * @return
     */
    public List getZipDtosCascader() {
        return null;
    }


}
